// vue方法
import { router,addRoutes } from "@/router"


// 自定义方法
import {getToken}  from "@/util/token"
import {toast} from "@/util/util" 

// api
import {getUserMenus} from "@/api/menu"


// 全局前置守卫
let hasGetInfo = false
router.beforeEach(async (to, from, next) => {
    // 显示loading
    // showFullLoading()

    const token = getToken()
    //  没有登录，强制跳转登录页
    if (!token && to.path != "/login" && to.path != "/register") {
        toast("请先登录！", "error")

        return next({
            path: "/login"
        })
    }
    if (token && to.path == "/login") {
        toast("无需重复登录！", "error")
        return next({
            path: from.path
        })
    }

    // 已登录
    let hasNewRoutes = false
    if (token && !hasGetInfo) {
        let user = JSON.parse(sessionStorage.getItem("currentUser"))
        let res = await getUserMenus({id:user.id})
        let menus = res.data.menuList
        hasGetInfo = true
        // 动态添加路由
        hasNewRoutes = addRoutes(menus)
    }



    // 设置页面的标题
    // let titel = (to.meta.title ? to.meta.title : '') + "-融媒体分发"
    // document.title = titel

    // // 如果未认证，跳转个人中心页面
    // if(store.state.user.is_auth != 1 && to.path!= "/user/user_home" && to.path!= "/login" && to.path!= "/auth" && to.path!= "/auth_company" && to.path!= "/agreement"){

    //     return next({
    //         path: "/user/user_home"
    //     })
    // }else{
    //     hasNewRoutes ? next(to.path) : next()
    // }
    next()
   
})


// 全局后置守卫
router.afterEach((to, from) => {
    // hideFullLoading()
})